<?php
//入住消费管理
class CheckinAction extends CommonAction {
        function _filter(&$map) {
       $key = trim($_REQUEST['keywords']);
         if(!empty($key)) {
             $map['checkin_no'] = array('like',"%".$key."%");
             $map['member_name'] =  array('like',"%".$key."%");
             $map['room_no'] =  array('like',"%".$key."%");
             $map['person_name'] =  array('like',"%".$key."%");
             $map['remark'] =  array('like',"%".$key."%");
             $map['_logic'] = "or";
             //$map['update_time'] = $key;//保证分页跳转正常,注意不要查询update_time
         }
         $start_time = $_REQUEST['start_time'];
         $end_time = $_REQUEST['end_time'];
         if(!empty($start_time)){
             $map['start_time'] = array('egt',strtotime($start_time));
         }
         if(!empty($end_time)){
             $map['end_time'] = array('elt',strtotime($end_time));
         }
    }

    function _before_index(){
       $this->assign('status',C('checkinStatus'));
    }

    function _before_add(){
        $this->assign('checkinStatus',C('checkinstatus'));
        $this->assign('orders',M('Order')->where('status > 0')->order('create_time desc')->limit(20)->findAll() );//暂时取最近的20个订单TODO
        $this->assign('member',M('Member')->where('status = 1')->findAll() );
        $this->assign('houses',M('House')->where('status = 1')->findAll() );
        $this ->assign('hotel',M('Hotel')->where('status = 1')->field('name,id')->findAll());
    }

     function _before_edit(){
         $this->assign('checkinStatus',C('checkinstatus'));
         $this->assign('contacts',M('Contact_record')->where('checkin_id = '.$_REQUEST['id'] )->findAll() );//借出记录状态
         /*
         $this->assign('cost_status',C('borrowstatus'));//借出记录状态
         $this->assign('cost_status_xf',C('coststatus'));//消费记录状态
         $this->assign('cost_types',C('Cost_type'));//费用类型
         //$this->assign('costs',M('Costdetail')->where('checkin_id ='.$_GET['id'])->findAll() );
         //$this->assign('borrows',M('Borrow')->where('checkin_id ='.$_GET['id'])->findAll() );
        //$this->assign('member',M('Member')->where('status = 1')->findAll() );
    
          * 
          */
          }
public function edit1(){
    $this->assign('checkinStatus',C('checkinstatus'));
    $this->assign('costs',M('Costdetail')->where('checkin_id ='.$_GET['id'])->order('update_time desc,create_time desc')->findAll() );
    $this->assign('borrows',M('Borrow')->where('checkin_id ='.$_GET['id'])->order('update_time,create_time desc')->findAll() );
    $this->assign('member',M('Member')->where('status = 1')->findAll() );
    parent::edit();
}

  function other_detail() {
    $this->assign('cost_status',C('borrowstatus'));//借出记录状态
    $this->assign('cost_status_xf',C('coststatus'));//消费记录状态
    $this->assign('cost_types',C('Cost_type'));//费用类型
    $this->assign('costs',M('Costdetail')->where('checkin_id ='.$_GET['id'])->findAll() );
    $this->assign('borrows',M('Borrow')->where('checkin_id ='.$_GET['id'])->findAll() );
    $this->display();
}

    public function insert(){
        //TODO暂时不记录person_id ，room_no需要在插入时进行转换记录
        //入住单不做时间限制
        /*if(isTooLong(strtotime( $_POST['start_time'] ),strtotime( $_POST['end_time'] ))== false ){
            $this->error("时间跨度超过一年半，无效订单！");
        }*/
        $end_time = !empty($_POST['end_realtime'])?$_POST['end_realtime']:$_POST['end_time'];//如果实际离开时间存在，取实际离开时间
            if( isOverlap( $_POST['room_id'], strtotime( $_POST['start_time'] ),strtotime( $end_time ) ) ) {
                $this->error("时间存在重叠！");
            }

        $data = $_POST;
        $data['start_time'] = empty($_POST['start_time'])?0:strtotime( $_POST['start_time'] );
        $data['end_time'] =empty($_POST['end_time'])?0:strtotime( $_POST['end_time'] );
        $data['end_realtime'] = empty($_POST['end_realtime'])?0:strtotime( $_POST['end_realtime'] );
        $data['alert_time'] = empty($_POST['alert_time'])?0:strtotime( $_POST['alert_time'] ); //提醒时间
        $data['balance_time'] = empty($_POST['balance_time'])?0:strtotime( $_POST['balance_time'] );//结账时间

        $data['create_time'] = time();
        $data['room_no'] = M('Room')->where('id ='.intval($_POST['room_id']) )->getField('room_no') ;
        $data['checkin_no'] = $this->genManNo(1);
        $data['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
        $data['check_status'] = 0;//永远设置为待审核
        
        $model = D('Checkin');
        if(false == $model ->create()){
            $this->error($model -> getError());
        }
        if(false !== $list = $model ->add($data)){
            if($data['status'] == 3){
                //入住结束，则计算积分.房租一元算一个积分
                M('Member')->where('id='.$data['member_id'])->setField('score',sumRentCost('', '', '', $data['member_id'], '', ''));
            }
            $jumpUrl = $_REQUEST['jumpUrl'];
           if(empty($jumpUrl)){
                $self_checkin_id = M('Checkin')->getField('max(id)');
                $jumpUrl = __APP__."/Checkin/edit/id/".$self_checkin_id; //返回编辑页面，可以新增联系记录，消费记录等 。
           }
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this-> success("新增入住单成功！");
        }
        else{
             $this->error("新增入住单失败！");
        }
    }

    /**
     * 增加消费记录
     */
    public function addCost(){
        //$data = $_POST;
        if(2 == $_GET['type']){//借还记录
            $data['name'] = $_POST['name'];
            $data['status'] = $_POST['status'];
            $model = D('Borrow');
        }
        else{//消费记录
             $data['cost_type'] = $_POST['cost_type'];
             $data['status'] = $_POST['status_xf'];
             $data['unit_price'] = $_POST['unit_price'];
             $data['start'] = $_POST['start'];
             $data['end'] = $_POST['end'];
             $data['total'] = $_POST['total'];
             $model = D('Costdetail');
        }
        $data['checkin_id'] = $_REQUEST['checkin_id'];
        $data['money'] = $_POST['money'];
        $data['remark'] = $_POST['remark'];
        //修正jeasyui传递时，只有日期没有时间的bug
         if(!empty($_POST['start_time'])){
            $start_time = $_POST['start_time'];
             if(!strpos($_POST['start_time'],":" ) ){//没有时间
                 $nowTime = date("H:i:s");
                 $start_time .= " ".$nowTime;
             }
        }

        if(!empty($_POST['end_time'])){
            $end_time = $_POST['end_time'];
             if(!strpos( $_POST['end_time'],":" ) ){//没有时间
                 $nowTime = date("H:i:s");
                 $end_time .= " ".$nowTime;
             }
        }
        $data['start_time'] = empty($_POST['start_time'])?0:strtotime( $start_time );
        $data['end_time'] =empty($_POST['end_time'])?0:strtotime( $end_time );
        $data['create_time'] = time();
        $data['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
        
        if(false == $model ->create()){
            $this->ajaxReturn('', $model -> getError(), 0);
        }
        if(false !== $list = $model ->add($data)){
            $this->ajaxReturn('', "新增成功！", 1);
        }
        else{
             $this->ajaxReturn('', '新增消费记录失败！', 0);
        }
        
    }

    public function update(){
        //入住单不做时间限制
        /*
        if(isTooLong(strtotime( $_POST['start_time'] ),strtotime( $_POST['end_time'] ))== false ){
            $this->error("时间跨度超过一年半，无效订单！");
        }*/
        $end_time = !empty($_POST['end_realtime'])?$_POST['end_realtime']:$_POST['end_time'];//如果实际离开时间存在，取实际离开时间
            if( isOverlap( $_POST['room_id'], strtotime( $_POST['start_time']),strtotime( $end_time),$_POST['id']  ) ) {
                $this->error("入住时间存在重叠！");
            }
        //如果状态为入住结束，则检查：
        //是否存在(有未付费用,未还物品,实际离开时间未处理,提醒时间未清空),就不能保存并弹出提醒.
        if($_POST['status'] == 3 ){
            if(!empty($_POST['alert_time']))
                $this->error('入住结束，提醒时间需清空！');
            if(empty($_POST['end_realtime']))
                $this->error('入住结束，实际离开时间未填写！');
            //费用未结清
            $costs = M('Costdetail')->where('checkin_id ='.$_POST['id'])->findAll(); 
            foreach ($costs as $key => $value) {
                if($value['status'] == 2){ //状态 “未付”
                     $this->error(getConfigVal($value['cost_type'],'cost_type').' 未结清！');
                    break;
                }else{
                    continue;
                }
                   
            }

            //东西未归还
            $borrows = M('Borrow')->where('checkin_id ='.$_POST['id'])->findAll(); 

            foreach ($borrows as $k => $bs) {
                if($bs['status'] == 0 ){    //借出状态
                     $this->error( $bs['name'].' 未归还！');
                    break;
                }else{
                    continue;
                }
                   
            }

        }
        
        $data = $_POST;
       $data['start_time'] = empty($_POST['start_time'])?0:strtotime( $_POST['start_time'] );
        $data['end_time'] =empty($_POST['end_time'])?0:strtotime( $_POST['end_time'] );
        $data['end_realtime'] = empty($_POST['end_realtime'])?0:strtotime( $_POST['end_realtime'] );
         $data['alert_time'] = empty($_POST['alert_time'])?0:strtotime( $_POST['alert_time'] );
        $data['balance_time'] = empty($_POST['balance_time'])?0:strtotime( $_POST['balance_time'] );
        $data['update_time'] = time();
        $data['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
        $data['check_status'] = 0;//永远设置为待审核
        $model = D('Checkin');
        if(false == $model ->create()){
            $this->error($model -> getError());
        }
        if(false !== $list = $model ->save($data)){
            if($data['status'] == 3){
                //入住结束，则计算积分.房租一元算一个积分
                M('Member')->where('id='.$data['member_id'])->setField('score',sumRentCost('', '', '', $data['member_id'], '', ''));
            }
           $jumpUrl = $_REQUEST['jumpUrl'];
           if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this->success ('入住单修改成功!');
        }
        else{
             $this->error("入住单修改失败！");
        }
    }

    public function getHotelData(){
        $result = M('Hotel')->where('status = 1')->field('name')->findAll();
        $this->ajaxReturn($result);
    }

    public function getMemberByOrder(){
        $orderid = $_POST['order_id'];
    $data = M('Order')->where('id ='.$orderid)->find();
    $data['member'] = getModelName($data['member_id'], 'Member');
    $data['start_time'] = toDate( $data['start_time'] );
    $data['end_time'] = toDate( $data['end_time'] );
    $data['house'] = getModelName($data['house_id'], 'House');
    $rooms = explode(',',$data['room_id']);
    $roomstr = "<td class='tLeft' id='room_td'>";
    foreach ($rooms as $key => $value) {
        $room_no = M('Room')->where('id ='.$value)->getField('room_no');
        $room_no = empty($room_no ) ? '暂无房间':$room_no;
        $roomstr .="<input type='radio' id='room_id' name='room_id' value='".$value."'/>".$room_no;
    }
    $data['rooms'] = $roomstr." </td>";
    $this->ajaxReturn($data, '',1);
    }

    public function getCostsJson(){
        import("@.ORG.Page"); // 导入分页类

        $count = M('Costdetail')->where('checkin_id ='.$_GET['checkin_id'])->count();
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
	$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10; //每页显示记录数

        $_GET['p'] = $_POST['page'];
        $Page = new Page($count, $rows ); // 实例化分页类 传入总记录数和每页显示的记录数
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('Costdetail')->where('checkin_id ='.$_GET['checkin_id'])->limit($Page->firstRow.','.$Page->listRows)->select();
        $currentRows = count($list);
        for($i=0;$i<$currentRows;$i++){//应该循环当前页
            $list[$i]['status_xf'] =  $list[$i]['status'];
            $list[$i]['start_time'] = toDate($list[$i]['start_time'],'Y-m-d H:i:s');
            $list[$i]['end_time'] = toDate($list[$i]['end_time'],'Y-m-d H:i:s');
            $list[$i]['create_time'] = toDate($list[$i]['create_time'],'Y-m-d H:i:s');
            $list[$i]['update_time'] = toDate($list[$i]['update_time'],'Y-m-d H:i:s');
            $list[$i]['remark'] = jsonFilter($list[$i]['remark']) ;//需要过滤特殊字符
        }
        $begin = "{\"total\":\"".$count."\",\"rows\":";
        echo $begin.array_to_json($list)."}";
    }

    public function getBorrowsJson(){
        import("@.ORG.Page"); // 导入分页类
        $count = M('Borrow')->where('checkin_id ='.$_GET['checkin_id'])->count();
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
	$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10; //每页显示记录数

        $_GET['p'] = $_POST['page'];
        $Page = new Page($count, $rows ); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = M('Borrow')->where('checkin_id ='.$_GET['checkin_id'])->limit($Page->firstRow.','.$Page->listRows)->select();
        $currentRows = count($list);
        for($i=0;$i<$currentRows;$i++){
            $list[$i]['cost_type'] =  $list[$i]['name'];
            $list[$i]['start_time'] = toDate($list[$i]['start_time'],'Y-m-d H:i:s');
            $list[$i]['end_time'] = toDate($list[$i]['end_time'],'Y-m-d H:i:s');
            $list[$i]['create_time'] = toDate($list[$i]['create_time'],'Y-m-d H:i:s');
            $list[$i]['update_time'] = toDate($list[$i]['update_time'],'Y-m-d H:i:s');
            $list[$i]['remark'] = jsonFilter($list[$i]['remark']) ;//需要过滤特殊字符
        }
        $begin = "{\"total\":\"".$count."\",\"rows\":";
        echo $begin.array_to_json($list)."}";
    }
    
}
?>
